package com.example.clientofDengJL;

import com.example.resourceofDengJL.bean.Student;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;
import java.util.Collections;

public class ClientofDengJL {
    private static final String BASE_URL = "http://localhost:8080/students";
    private final RestTemplate restTemplate = new RestTemplate();

    /**
     * 添加学生信息
     */
    public void addStudent(Student student) {
        try {
            ResponseEntity<String> response = restTemplate.postForEntity(
                    BASE_URL, student, String.class
            );
            System.out.println(response.getBody());
        } catch (HttpClientErrorException e) {
            System.out.println("添加失败: " + e.getResponseBodyAsString());
        } catch (Exception e) {
            System.out.println("网络错误: " + e.getMessage());
        }
    }

    /**
     * 查询所有学生 - 添加异常处理
     */
    public List<Student> getAllStudents() {
        try {
            ResponseEntity<Student[]> response = restTemplate.getForEntity(BASE_URL, Student[].class);
            return Arrays.asList(response.getBody());
        } catch (HttpClientErrorException e) {
            System.out.println("查询失败: " + e.getResponseBodyAsString());
            return Collections.emptyList();
        } catch (Exception e) {
            System.out.println("网络错误: " + e.getMessage());
            return Collections.emptyList();
        }
    }

    /**
     * 查询指定学号学生 - 添加异常处理
     */
    public Student getStudentById(String id) {
        try {
            String url = BASE_URL + "/" + id;
            return restTemplate.getForObject(url, Student.class);
        } catch (HttpClientErrorException e) {
            if (e.getStatusCode().value() == 404) {
                System.out.println("未找到学号为 " + id + " 的学生");
            } else {
                System.out.println("查询失败: " + e.getResponseBodyAsString());
            }
            return null;
        } catch (Exception e) {
            System.out.println("网络错误: " + e.getMessage());
            return null;
        }
    }

    public static void main(String[] args) {
        ClientofDengJL client = new ClientofDengJL();

        // 添加学生
        Student student1 = new Student("1", "张三", "2000-01-01");
        Student student2 = new Student("2", "李四", "2001-02-02");
        client.addStudent(student1);
        client.addStudent(student2);

        // 查询所有学生
        List<Student> allStudents = client.getAllStudents();
        System.out.println("所有学生信息：");
        allStudents.forEach(System.out::println);

        // 查询指定学号学生
        Student targetStudent = client.getStudentById("1");
        if (targetStudent != null) {
            System.out.println("学号1的学生信息：" + targetStudent);
        }

        System.out.println("请打开前端界面 index.html");
    }
}